package com.lp.product.controller;

import com.lp.product.common.DecreaseStockInput;
import com.lp.product.dto.CartDTO;
import com.lp.product.vo.ProductInfoVO;
import com.lp.product.vo.ProductVO;
import com.lp.product.vo.ResultVO;
import com.lp.product.dataobject.ProductCategory;
import com.lp.product.dataobject.ProductInfo;
import com.lp.product.repository.ProductCategoryRepository;
import com.lp.product.repository.ProductInfoRepository;
import com.lp.product.service.ProductService;
import com.lp.product.util.ResultVOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LIPENGAK
 * @Description: 类描述
 * @date 2018-10-30 00:04
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductCategoryRepository productCategoryRepository;
    @Autowired
    private ProductInfoRepository productInfoRepository;

    @Autowired
    private ProductService productService;
    /**
     * 1. 查询所有在架的商品
     * 2. 获取类目列表
     * 3. 查询类目
     * 4. 构造数据
     */
    @GetMapping("/list")
    public ResultVO<ProductVO> list(){
        //获取所有商品
        List<ProductInfo> productList = productInfoRepository.findAll();
        //获取所有类目
        List<Integer> categoryTypeList = productList.stream().map(ProductInfo::getCategoryType).collect(Collectors.toList());
        //查询类目
        List<ProductCategory> categoryList = productCategoryRepository.findByCategoryTypeIn(categoryTypeList);
        //构造数据
        List<ProductVO> productVOS = new ArrayList<>();
        for (ProductCategory catetory: categoryList){
            ProductVO productVO = new ProductVO();
            productVO.setCategoryType(catetory.getCategoryType());
            productVO.setCategoryName(catetory.getCategoryName());

            List<ProductInfoVO> productInfoVOS = new ArrayList<>();
            for (ProductInfo productInfo : productList ){
                ProductInfoVO productInfoVO = new ProductInfoVO();
                BeanUtils.copyProperties(productInfo,productInfoVO);
                productInfoVOS.add(productInfoVO);
            }
            productVO.setFoods(productInfoVOS);
            productVOS.add(productVO);
        }

        return ResultVOUtil.success(productVOS);
    }

    /**
     * 根据订单里面的商品ids获取商品列表（给订单服务用）
     * @param productIds
     * @return
     */
    @PostMapping("/listForOrder")
    public List<ProductInfo> listForOrder(@RequestBody List<String> productIds){
        return productService.findList(productIds);
    }


    @PostMapping("/decreaseStock")
    public void decreaseStock(@RequestBody List<DecreaseStockInput> decreaseStockInputList){
        productService.decreaseStock(decreaseStockInputList);
    }

}
